package com.keyinong.dingcan.pay;

import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.keyinong.dingcan.R;
import com.keyinong.dingcan.Tools.HttpTools;
import com.keyinong.dingcan.view.FanqiedingcanActivity;
import com.keyinong.dingcan.view.UsecouponsActivity;
import com.loopj.android.http.JsonHttpResponseHandler;

public class BalancepayActivity extends Activity {
	
	View iscatview = null;
	private TextView tv_price;
	private TextView tv_balance;
	private Button btn_pay;
	private ImageButton ib_fanhui;
	HttpTools httpTools=null;
	private String token;
	private TextView tv_shengyu;
	private RelativeLayout rl_youhuiquan;
	private String orderid;
	private int length;
	private String off;
	private String price;
	private String couponid="0";
	private boolean flag=true;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_blancepay);
		initRes();
	}

	private void initRes() {
		tv_price=(TextView)findViewById(R.id.tv_price);
		tv_balance=(TextView)findViewById(R.id.tv_balance);
		btn_pay=(Button)findViewById(R.id.btn_pay);
		ib_fanhui=(ImageButton)findViewById(R.id.ib_fanhui);
		tv_shengyu=(TextView)findViewById(R.id.tv_shengyu);
		rl_youhuiquan=(RelativeLayout)findViewById(R.id.rl_youhuiquan);
		price = getIntent().getStringExtra("price");		
		orderid=getIntent().getStringExtra("orderid");
		//		off = getIntent().getStringExtra("off");
		tv_price.setText("￥"+price);
		//		tv_price.setText(price);
		btn_pay.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (flag==true) {
					if (!couponid.equals("0")) {
					useconpons();
					Log.i("zq", "useconpons-------");
				}else {
					Balancepay();
					Log.i("zq", "Balancepay-------");
				}
//					Log.i("ceshi", "flag-------true");
				}
				flag=false;
				
			}
		});
		ib_fanhui.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
//				if (!couponid.equals("0")||!couponid.equals("null")) {
//					couponsdialog();
//				}else {
					finish();
//				}		
			}
		});
		Balance();
		Coupons();
		rl_youhuiquan.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent();
				intent.setClass(BalancepayActivity.this, UsecouponsActivity.class);
				intent.putExtra("orderid", orderid);
				intent.putExtra("price", price);
				startActivityForResult(intent, 2);
				//	finish();
			}
		});
	}

	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
		//		SharedPreferences sp=getSharedPreferences("spCoupons", Context.MODE_PRIVATE);
		//		String off = sp.getString("off", "");
		//		tv_shengyu.setText("�?"+off);
		//		Coupons();
	}
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		Log.i("zq", "requestCode---------"+requestCode);
		Log.i("zq", "resultCode---------"+resultCode);
		//		Log.i("zq", "data---------"+data.getStringExtra("orderid"));
		switch(resultCode){  
		case 1:  
//			couponid
			tv_shengyu.setText("可用"+length+"张");
			price = getIntent().getStringExtra("price");
			tv_price.setText("￥"+price);
		case 2:  
			Bundle bundle = data.getExtras();  
			off = bundle.getString("off");
			couponid = bundle.getString("couponid");
			price = getIntent().getStringExtra("price");
			if (!off.equals("0")) {
				rl_youhuiquan.setVisibility(View.VISIBLE);
				//off = getIntent().getStringExtra("off");
				Log.i("zq", "off-----"+off);
				Log.i("zq", "couponid-----"+couponid);
				double youhui = Double.parseDouble(price)-Integer.parseInt(off);
				if (youhui<=0) {
					tv_price.setText("￥"+"0");
				}else {
					tv_price.setText("￥"+youhui);
				}
				
				tv_shengyu.setText("减"+off+"元");
			}

		}  
	}
	private void Balance() {
		SharedPreferences sp=getSharedPreferences("spReg", Context.MODE_PRIVATE);
		token = sp.getString("data", "");
		if (httpTools == null) {
			httpTools = new HttpTools(BalancepayActivity.this);
		}
		httpTools.getBalance(token,new JsonHttpResponseHandler() {

			@Override
			public void onSuccess(int statusCode, Header[] headers,
					JSONObject response) {
				super.onSuccess(statusCode, headers, response);
				try {
					boolean code = response.getBoolean("code");
					String msg = response.getString("msg");
					Log.i("zq", "balance---"+response.toString());
					if (code == true) {
						String data=response.getString("data");
						//						Toast.makeText(BalancepayActivity.this, msg, Toast.LENGTH_SHORT).show();
						//										view.setBackgroundResource(R.drawable.shouchang1);
						tv_balance.setText("￥"+data);
					} else {
						Toast.makeText(BalancepayActivity.this, msg, Toast.LENGTH_SHORT).show();
					}
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

		});
	}

	private void Balancepay() {
		SharedPreferences sp=getSharedPreferences("spReg", Context.MODE_PRIVATE);
		token = sp.getString("data", "");

		//		Log.i("zq", "balancepayorderid---"+orderid);
		if (httpTools == null) {
			httpTools = new HttpTools(BalancepayActivity.this);
		}
		httpTools.submitpay(token,orderid,new JsonHttpResponseHandler() {

			@Override
			public void onSuccess(int statusCode, Header[] headers,
					JSONObject response) {
				super.onSuccess(statusCode, headers, response);
				try {
					boolean code = response.getBoolean("code");
					String msg = response.getString("msg");
					Log.i("zq", "balancepay---"+response.toString());
					if (code == true) {
						//						String data=response.getString("data");
						Toast.makeText(BalancepayActivity.this, msg, Toast.LENGTH_SHORT).show();
						Intent intent = new Intent();
						intent.setClass(BalancepayActivity.this, FanqiedingcanActivity.class);
						startActivity(intent);
						finish();
						//										view.setBackgroundResource(R.drawable.shouchang1);
						//						tv_balance.setText("�?"+data+"�?");
					} else {
						Toast.makeText(BalancepayActivity.this, msg, Toast.LENGTH_SHORT).show();
					}
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

		});
	}
	
	private void useconpons() {
		SharedPreferences sp=getSharedPreferences("spReg", Context.MODE_PRIVATE);
		token = sp.getString("data", "");

		//		Log.i("zq", "balancepayorderid---"+orderid);
		if (httpTools == null) {
			httpTools = new HttpTools(BalancepayActivity.this);
		}
		httpTools.updateCoupon(token,couponid,orderid,new JsonHttpResponseHandler() {

			@Override
			public void onSuccess(int statusCode, Header[] headers,
					JSONObject response) {
				super.onSuccess(statusCode, headers, response);
				try {
					boolean code = response.getBoolean("code");
					String msg = response.getString("msg");
//					Log.i("zq", "balancepay---"+response.toString());
					if (code == true) {
						//						String data=response.getString("data");
//						Toast.makeText(BalancepayActivity.this, msg, Toast.LENGTH_SHORT).show();
//						Intent intent = new Intent();
//						intent.setClass(BalancepayActivity.this, FanqiedingcanActivity.class);
//						startActivity(intent);
						//										view.setBackgroundResource(R.drawable.shouchang1);
						//						tv_balance.setText("�?"+data+"�?");
						Log.i("zq", "useconpons----成功");
						resetbalancepay();
					} else {
						Toast.makeText(BalancepayActivity.this, msg, Toast.LENGTH_SHORT).show();
					}
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

		});
	}
	
	
	private void Coupons() {
		SharedPreferences sp=getSharedPreferences("spReg", Context.MODE_PRIVATE);
		token = sp.getString("data", "");
		String orderid=getIntent().getStringExtra("orderid");
		//		Log.i("zq", "balancepayorderid---"+orderid);
		if (httpTools == null) {
			httpTools = new HttpTools(BalancepayActivity.this);
		}
		httpTools.getCoupons(token,orderid, new JsonCoupons());
	}
	public class JsonCoupons extends JsonHttpResponseHandler {
		@Override
		public void onSuccess(int statusCode, Header[] headers,
				JSONArray response) {
			// TODO Auto-generated method stub
			super.onSuccess(statusCode, headers, response);
			try {
				Log.i("info",response.toString());
				for (int i = 0; i < response.length(); i++) {
					JSONObject data = response.getJSONObject(i);
					String id=data.getString("id");
					String couponno=data.getString("couponno");
					String more=data.getString("more");
					String off=data.getString("off");
					//					typelist.add(new AddressEntity(id, name, lot, lat));
				}
				length=response.length();
				if (response.length()==0) {
					rl_youhuiquan.setVisibility(View.GONE);
				}else {
					rl_youhuiquan.setVisibility(View.VISIBLE);
					//					if (off.equals("null")) {
					//						tv_shengyu.setText("�?"+off);
					//					}else {
					tv_shengyu.setText("可用"+response.length()+"张");
					//					}

				}
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}
	}
	
	/**支付失败返回优惠券*/
	private void resetconpons() {
		SharedPreferences sp=getSharedPreferences("spReg", Context.MODE_PRIVATE);
		token = sp.getString("data", "");

		//		Log.i("zq", "balancepayorderid---"+orderid);
		if (httpTools == null) {
			httpTools = new HttpTools(BalancepayActivity.this);
		}
		httpTools.resetCoupon(token,couponid,orderid,new JsonHttpResponseHandler() {

			@Override
			public void onSuccess(int statusCode, Header[] headers,
					JSONObject response) {
				super.onSuccess(statusCode, headers, response);
				try {
					boolean code = response.getBoolean("code");
					String msg = response.getString("msg");
					Log.i("zq", "resetconpons---"+response.toString());
					if (code == true) {
						
					} else {
						Toast.makeText(BalancepayActivity.this, msg, Toast.LENGTH_SHORT).show();
					}
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

		});
	}
	
	/**支付失败*/
	private void resetbalancepay() {
		SharedPreferences sp=getSharedPreferences("spReg", Context.MODE_PRIVATE);
		token = sp.getString("data", "");

		//		Log.i("zq", "balancepayorderid---"+orderid);
		if (httpTools == null) {
			httpTools = new HttpTools(BalancepayActivity.this);
		}
		httpTools.submitpay(token,orderid,new JsonHttpResponseHandler() {

			@Override
			public void onSuccess(int statusCode, Header[] headers,
					JSONObject response) {
				super.onSuccess(statusCode, headers, response);
				try {
					boolean code = response.getBoolean("code");
					String msg = response.getString("msg");
					Log.i("zq", "balancepay---"+response.toString());
					if (code == true) {
						//						String data=response.getString("data");
						Toast.makeText(BalancepayActivity.this, msg, Toast.LENGTH_SHORT).show();
						Intent intent = new Intent();
						intent.setClass(BalancepayActivity.this, FanqiedingcanActivity.class);
						startActivity(intent);
						finish();
						//										view.setBackgroundResource(R.drawable.shouchang1);
						//						tv_balance.setText("�?"+data+"�?");
					} else {
						Toast.makeText(BalancepayActivity.this, msg, Toast.LENGTH_SHORT).show();
						resetconpons();
					}
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

		});
	}
	
	
	/**优惠券弹�?*/
	private void couponsdialog() {

		final Dialog dialog = new Dialog(BalancepayActivity.this);
		dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);

		iscatview = LayoutInflater.from(BalancepayActivity.this).inflate(
				R.layout.dialog_phone, null);
		//			TextView tital = (TextView) iscatview.findViewById(R.id.tital);
		//			TextView tv_phone = (TextView) iscatview.findViewById(R.id.tv_phone);
		TextView tital = (TextView) iscatview.findViewById(R.id.tital);
		TextView tv_no = (TextView) iscatview.findViewById(R.id.tv_no2);
		TextView tv_yes = (TextView) iscatview.findViewById(R.id.tv_yes2);
		//			tv_phone.setText(phone);
		//			tv_phone.setVisibility(View.GONE);
		//			tital.setText("该上下班有人加入，拼车是否完�??");
		tital.setText("优惠券已使用，是否退出出支付？");
		tv_no.setText("取消");
		tv_yes.setText("确定");
		dialog.setContentView(iscatview);
		dialog.show();
		tv_no.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
//				Log.i("ceshi", "qucan---"+qucan);
//				Log.i("ceshi", "fee---"+fee);
				dialog.dismiss();
			}
		});
		tv_yes.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				finish();
				dialog.dismiss();
			}
		});
	}

}
